/**
 * 安排模型
 */
define(function(require, exports, module) {

    var Backbone = require('backbone'),
        _ = require('underscore'),
        moment = require('moment'),
        TimeModel = require('model/time'),
        TimeCollection = require('collection/time');

    module.exports = Backbone.Model.extend({
        defaults: {
            topic: '', //主题
            time: '', //时间
            address: '', //地点
            content: '', //内容
            allowActive: false, //是否允许主动申请
            posterUrl: '', //海报链接
            owner: true //是否自己创建
        },
        idAttribute: 'objectId', 
        initialize: function () {
            this.time = new TimeModel;
            this.time.collection = new TimeCollection;
            if(this.get('time').length > 0) {
                this.time.id = this.get('time');
                this.time.fetch();
            }
        },
        validate: function(attrs, options) {
            var message = '';

            var required = _.pick(attrs, (this.isNew() ? ['topic','address'] : ['topic','time','address']));
            _.each(required, function(value, key) {
                if(_.isEmpty(value)) message += key + ' 不能为空<br>';
            });

            if(!_.isBoolean(attrs.allowActive)) message += 'allowActive 必须为bool类型<br>';

            if(!_.isEmpty(message)) return message;
        },
        isMine: function() {
            return this.get('owner');
        },
        toForm: function() {
            var data = this.toJSON();
            data.allowActive = data.allowActive ? ['yes'] : ['no'];
            data.startAt = moment.unix(this.time.get('startAt')).format('YYYY-MM-DDTHH:mm');
            data.endAt = moment.unix(this.time.get('endAt')).format('YYYY-MM-DDTHH:mm');
            return data;
        },
        fromForm: function(data) {
            var self = this,
                now = parseInt(moment().format('X'));
            //数据格式转换
            data.allowActive = data.allowActive[0]==='yes' ? true : false;
            data.startAt = parseInt(moment(data.startAt, 'YYYY-MM-DDTHH:mm').format('X'));
            data.endAt = parseInt(moment(data.endAt, 'YYYY-MM-DDTHH:mm').format('X'));
            //var timeList = new TimeCollection;
            //创建聚会
            var _createFromForm = function(data, force) {
                //设置非时间属性
                var _data = _.pick(data, ['topic','address','content','allowActive','posterUrl']);
                self.set(_data);
                //验证
                if(!self.isValid()) return {code: 1, message: self.validationError};

                if(data.startAt <= now) return {code: 1, message: '开始时间必须在当前时间之后'};
                //获取时段模型，会创建新的模型
                //self.getTime();
                //if(!self.time) return {code: 1, message: '无法创建时间'};
                //设置时段
                self.time.set({
                    startAt: data.startAt,
                    endAt: data.endAt
                });
                if(!self.time.isValid()) return {code: 1, message: self.time.validationError};

                var freeList = force===true ? [] : self.time.collection.freeTime(self.time.toJSON());
                if(force===true || freeList.length===1 && self.time.equal(freeList[0])) {
                    //时段可用，注册时段
                    self.time.save(null, {wait: true});
                    if(self.time.id) {
                        self.set('time', self.time.id);
                    }
                    else {
                        return {code: 1, message: '无法保存时间'};
                    }
                } else {
                    //时段不可用
                    return {code: 2, message: '该时间段已有其他安排', freeTime: freeList};
                }
                return {code: 0, message: ''};
            };
            //编辑聚会
            var _updateFromForm = function(data, force) {
                if(!self.isMine()) return {code: 1, message: '不是创建者，不能编辑'};
                //self.getTime();
                //if(!self.time) return {code: 1, message: '无法获取时间'};
                if(self.time.isEnded()) return {code: 1, message: '已结束，不能修改'};

                //修改非时间属性
                var enabled = self.time.isStarted() ? ['content'] : ['topic','address','content','allowActive','posterUrl'];
                var _data = _.pick(data, enabled);
                self.set(_data);
                //验证有效性
                if(!self.isValid()) return {code: 1, message: self.validationError};

                if(!self.time.isStarted() && data.startAt <= now) {
                    //不允许把开始时间改到当前时间之前
                    return {code: 1, message: '开始时间必须在当前时间之后'};
                }

                //修改后的时间
                var updatedTime = {
                    startAt: self.time.isStarted() ? self.time.get('startAt') : data.startAt,
                    endAt: data.endAt
                };

                //不允许把结束时间改到当前时间之前
                if(updatedTime.endAt <= now) return {code: 1, message: '结束时间必须在当前时间之后'};

                if(!self.time.equal(updatedTime)) {
                    var newTime = new TimeModel(updatedTime);
                    //验证
                    if(!newTime.isValid()) return {code: 1, message: newTime.validationError};
                    var freeList = force===true ? [] : self.time.collection.freeTime(newTime.toJSON(), self.time.toJSON());
                    if(force===true || freeList.length===1 && newTime.equal(freeList[0])) {
                        //时段可用，更新时间
                        self.time.set(newTime.toJSON());
                        self.time.save(null, {wait: true});
                        newTime.destroy();
                    } else {
                        //时段不可用
                        return {code: 2, message: '该时间段已有其他安排', freeTime: freeList};
                    }
                }
                return {code: 0, message: ''};
            };

            return this.isNew() ? _createFromForm(data) : _updateFromForm(data);
            
        }
    });
});